//
//  HJCommentView.m
//  project
//
//  Created by yefei on 2019/7/20.
//  Copyright © 2019 健健. All rights reserved.
//

#import "HJCommentView.h"
#import "GKBallLoadingView.h"
#import "HJViewModel.h"
#import "HJVideoModel.h"
#import "HJCommentCell.h"
#import "YFJourneyModel.h"

@interface HJCommentView ()<UITableViewDataSource, UITableViewDelegate,UITextViewDelegate>
/**
 蒙版
 */
@property (nonatomic, strong) UIVisualEffectView *effectView;
/**
 顶部视图
 */
@property (nonatomic, strong) UIView *topView;
/**
 数组
 */
@property (nonatomic, strong) UILabel *countLabel;
/**
 关闭按钮
 */
@property (nonatomic, strong) UIButton *closeBtn;
/**
 UITableView
 */
@property (nonatomic, strong) UITableView *tableView;

/**
 输入框
 */
@property (weak, nonatomic) IBOutlet UITextView *inputTextView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *text_h;

/**
 iphone X以上的遮挡视图
 */
@property (nonatomic,strong) UIView * btmView;
/**
 占位placeHolder
 */
@property (nonatomic,strong) UILabel * placeHolder;

/**
 A数据源
 */
@property (nonatomic,strong) NSMutableArray <HJCommentModel *>*dataArray;

/**
 页
 */
@property (nonatomic, assign) NSInteger page;
@property (nonatomic,strong) HJVideoModel * videoModel;

/**
 总页码
 */
@property (nonatomic, strong) NSString * totalPage;
/**
 评论点击
 */
@property (nonatomic,strong) NSIndexPath * indexPath;
@property (nonatomic,assign) BOOL isFirst;

/**
 二级评论的model
 */
@property (nonatomic,strong) HJCommentModel * replyModel;
@property (nonatomic,assign) BOOL isReply;// 是否是二级评论回复

@end
static NSString * const identifier = @"HJCommentCell";
@implementation HJCommentView
// 适配比例
#define ADAPTATIONRATIO     SCREEN_WIDTH / 750.0f

-(instancetype)init {
    if (self = [super init]) {
        self = [[NSBundle mainBundle] loadNibNamed:@"HJCommentView" owner:nil options:nil].firstObject;
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.7];
        self.page = 1;
        self.indexPath = [NSIndexPath indexPathWithIndex:0];
        self.isFirst = NO;
        self.isReply = NO;
        self.inputTextView.delegate = self;
        
        [mNotificationCenter addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardDidShowNotification object:nil];
        [mNotificationCenter addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
        [self addSubview:self.topView];
        [self addSubview:self.effectView];
        [self addSubview:self.countLabel];
        [self addSubview:self.closeBtn];
        [self addSubview:self.tableView];
        [self insertSubview:self.inputTextView aboveSubview:self.tableView];
        [self.inputTextView addSubview:self.placeHolder];
        
        @weakify(self)
        [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
            @strongify(self)
            make.left.top.right.equalTo(self);
            make.height.mas_equalTo(ADAPTATIONRATIO * 80.0f);
        }];
        
        [self.effectView mas_makeConstraints:^(MASConstraintMaker *make) {
            @strongify(self)
            make.edges.equalTo(self);
        }];
        
        [self.countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            @strongify(self)
            make.center.equalTo(self.topView);
        }];
        
        [self.closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            @strongify(self)
            make.centerY.equalTo(self.topView);
            make.right.equalTo(self).offset(-ADAPTATIONRATIO * 16.0f);
            make.width.height.mas_equalTo(ADAPTATIONRATIO * 36.0f);
        }];
        
        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            @strongify(self)
            make.left.right.bottom.equalTo(self);
            make.top.equalTo(self.topView.mas_bottom);
        }];
        
        [self.placeHolder mas_makeConstraints:^(MASConstraintMaker *make) {
            @strongify(self)
            make.left.equalTo(self.inputTextView).offset(15);
            make.centerY.equalTo(self.inputTextView);
            make.height.mas_equalTo(18);
        }];
        
        if (SAFE_AREA_HEIGHT>0) {
            [self.btmView mas_makeConstraints:^(MASConstraintMaker *make) {
                @strongify(self)
                make.left.bottom.right.equalTo(self);
                make.height.mas_equalTo(SAFE_AREA_HEIGHT);
            }];
        }
    }
    return self;
}

/**
 初始化数据源数组
 @return dataArray
 */
-(NSMutableArray<HJCommentModel *> *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(void)loadDataWorkWithModel:(HJVideoModel *)model {
    self.videoModel = model;
    GKBallLoadingView *loadingView = [GKBallLoadingView loadingViewInView:self.tableView];
    [loadingView startLoading];
    self.countLabel.text = [NSString stringWithFormat:@"%@条评论", model.reviewAmount];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSDictionary * params = @{
                                  @"albumId": model.albumId,
                                  @"pageCurrent": @(self.page),
                                  @"pageSize": @"20",
                                  @"order":@"true"
                                  };
        NSString * url = [Api stringByAppendingString:ReviewListApi];
        [HJHttpTool get:url params:params success:^(HJResponeds *result) {
            [loadingView stopLoading];
            [loadingView removeFromSuperview];
            NSArray <HJCommentModel*>*array = [NSArray yy_modelArrayWithClass:[HJCommentModel class] json:result.data[@"records"]];
            if (!array) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
                return;
            }
            self.totalPage = result.data[@"pages"];
            [self.dataArray addObjectsFromArray:array];
            [self.tableView reloadData];
        } failure:^(id result) {
            [YFHud showError:result];
        }];
    });
}
-(HJViewModel *)viewModel {
    return [HJViewModel new];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJCommentCell * commentCell = [tableView cellForRowAtIndexPath:indexPath];
    if (!commentCell) {
        commentCell = [[HJCommentCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    // 评论
    commentCell.commentIndex = indexPath;
    commentCell.commentModel = self.dataArray[indexPath.row];
    // 二级点击block
    @weakify(self)
    commentCell.CommentDidClickBlock = ^(HJCommentModel * _Nonnull replyCommentModel, NSIndexPath * _Nonnull commentIndex) {
        @strongify(self)
        self.replyModel = replyCommentModel;
        self.indexPath = commentIndex;
        [self.inputTextView becomeFirstResponder];
        self.isReply = YES;
    };
    return commentCell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.dataArray[indexPath.row].reviewList.count>0) {
        return self.dataArray[indexPath.row].replyHeight;
    }
    return self.dataArray[indexPath.row].cellHeight;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.indexPath = indexPath;
    self.isFirst = YES;
    [self.inputTextView becomeFirstResponder];
}

#pragma mark -- 加载UI控件
-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 120;
        _tableView.backgroundColor = [UIColor clearColor];
        CGFloat height = SAFE_AREA_HEIGHT +50 ;
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, height, 0);
        @weakify(self)
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            @strongify(self)
            self.page++;
            if (self.page > [self.totalPage integerValue]) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else {
                [self loadDataWorkWithModel:self.videoModel];
            }
        }];
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _tableView;
}

- (UIButton *)closeBtn {
    if (!_closeBtn) {
        _closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_closeBtn setImage:[UIImage imageNamed:@"guanbi"] forState:0];
        @weakify(self)
        [[_closeBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            if (self.close) {
                self.close();
            }
        }];
    }
    return _closeBtn;
}

- (UILabel *)countLabel {
    if (!_countLabel) {
        _countLabel = [UILabel new];
        _countLabel.font = [UIFont systemFontOfSize:17.0f];
        _countLabel.textColor = [UIColor whiteColor];
    }
    return _countLabel;
}

- (UIVisualEffectView *)effectView {
    if (!_effectView) {
        UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
        _effectView = [[UIVisualEffectView alloc] initWithEffect:blur];
    }
    return _effectView;
}

- (UIView *)topView {
    if (!_topView) {
        _topView = [UIView new];
        _topView.backgroundColor = HJColorRGB(23);
        CGRect frame = CGRectMake(0, 0, SCREEN_WIDTH, ADAPTATIONRATIO * 100.0f);
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:frame byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(5, 5)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = frame;
        maskLayer.path = maskPath.CGPath;
        _topView.layer.mask = maskLayer;
    }
    return _topView;
}

-(UILabel *)placeHolder {
    if (!_placeHolder) {
        _placeHolder = [UILabel new];
        _placeHolder.text = @"评论 说点好听的~";
        _placeHolder.textColor = [UIColor lightGrayColor];
        _placeHolder.font = [UIFont systemFontOfSize:16];
    }
    return _placeHolder;
}
-(UIView *)btmView {
    if (!_btmView) {
        _btmView = [UIView new];
        _btmView.backgroundColor = [UIColor blackColor];
        [self addSubview:_btmView];
    }
    return _btmView;
}
#pragma mark --UITextViewDelegate 计算textView的高
-(void)textViewDidChange:(UITextView *)textView {
    if (!textView.text.length || [textView.text isEqualToString:@""]) {
        self.placeHolder.hidden = NO;
    }else {
        self.placeHolder.hidden = YES;
    }
    CGRect frame = textView.frame;
    CGSize size = [textView sizeThatFits:CGSizeMake(frame.size.width, CGFLOAT_MAX)];
    if (size.height > 100) {
        self.inputTextView.scrollEnabled = YES;
        return;
    }
    if (size.height < 50) {
        size.height = 50;
    }
    WS(weakSelf)
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIView performWithoutAnimation:^{
            weakSelf.text_h.constant = size.height+2;
        }];
    });
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if (range.location>=200) return NO;
    if ([text isEqualToString:@"\n"]) {
        if (textView.text.length) {
            NSMutableDictionary * params = [NSMutableDictionary dictionary];
            params[@"albumId"] = self.videoModel.albumId;
            params[@"content"] = textView.text;
            if (!self.isReply) {
                if (!self.isFirst) {// 一级评论
                    params[@"toUserId"] = self.videoModel.user.userId;
                } else {// 点击一级评论了之后 给二级展示
                    params[@"toUserId"] =  self.dataArray[self.indexPath.row].toUser.userId;
                    params[@"reviewId"] = self.dataArray[self.indexPath.row].reviewId;
                }
                [self commentRequestWithParams:params];
            } else { // 二级评论回复
                params[@"toUserId"] = self.replyModel.toUser.userId;
                params[@"reviewId"] = self.replyModel.reviewId;
    
                [self commentRequestWithParams:params];
            }
        }
        return NO;
    }
    return YES;
}

-(void)commentRequestWithParams:(NSDictionary *)params {
    
    [self.inputTextView resignFirstResponder];
    self.text_h.constant = 0.0;
    if (params.allValues.count==0) return;
    @weakify(self)
    [[self viewModel] loadReviewSubMitDataWorkWithParams:params success:^(id  _Nonnull data) {
        @strongify(self)
        int count = self.videoModel.reviewAmount.intValue;
        count++;
        self.videoModel.reviewAmount = [NSString stringWithFormat:@"%d",count];
        // 更新评论数
        [mNotificationCenter postNotificationName:NotificationCommentCount object:nil userInfo:nil];
        self.inputTextView.text = @"";
        self.placeHolder.hidden = NO;
        if (!self.isFirst && !self.isReply) {
            [self.dataArray insertObject:(HJCommentModel *)data atIndex:0];
            self.countLabel.text = [NSString stringWithFormat:@"%zd条评论",self.dataArray.count];
            [self.tableView reloadData];
            return;
        }
        HJCommentModel * model = (HJCommentModel *)data;
        // 计算出新的Cell总高，高度
        CGFloat allCellHeight = 0.0;
        if (self.isFirst && !self.isReply) {
            allCellHeight = self.dataArray[self.indexPath.row].cellHeight + model.cellHeight;
        }else {
            allCellHeight = self.dataArray[self.indexPath.row].replyHeight + model.cellHeight;
        }
        self.dataArray[self.indexPath.row].replyHeight = allCellHeight;
        NSMutableArray * secondArray = [NSMutableArray arrayWithArray:self.dataArray[self.indexPath.row].reviewList];
        [secondArray insertObject:model atIndex:0];
        self.dataArray[self.indexPath.row].reviewList = [NSArray arrayWithArray:secondArray];
        self.countLabel.text = [NSString stringWithFormat:@"%zd条评论",self.dataArray.count];
        [self.tableView reloadRowsAtIndexPaths:@[self.indexPath] withRowAnimation:UITableViewRowAnimationNone];
        [mNotificationCenter postNotificationName:NotificationCommentCount object:nil userInfo:nil];
        self.isFirst = NO;
        self.isReply = NO;
    } failure:^(NSString * _Nonnull error) {
        [YFHud showError:error];
    }];
}

#pragma mark -- 键盘弹起通知
-(void)keyboardWillShow:(NSNotification *)notification {
    CGRect keyboardFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardH = keyboardFrame.size.height-SAFE_AREA_HEIGHT;
    self.inputTextView.transform = CGAffineTransformMakeTranslation(0, -keyboardH);
}

#pragma mark -- 键盘收回通知
-(void)keyboardWillHide:(NSNotification *)notification {
    self.inputTextView.transform = CGAffineTransformIdentity;
}


@end
